package admin

import (
	"github.com/labstack/echo/v4"
	"techoiceness.com/aiagent/llm-gateway/internal/entity"
	"techoiceness.com/aiagent/llm-gateway/internal/server/response"
)

// GetLLMMessages 获取LLM交互消息列表
func (h *AdminHandler) GetLLMMessages(c echo.Context) error {
	req := new(GetLLMMessagesRequest)
	if err := c.Bind(req); err != nil {
		return response.BadRequest(c, "Invalid request format")
	}
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.Limit <= 0 || req.Limit > 100 {
		req.Limit = 20
	}

	var messages []entity.LLMMessage
	var total int64

	tx := h.db.Model(&entity.LLMMessage{})
	if req.ConversationID != "" {
		tx = tx.Where("conversation_id = ?", req.ConversationID)
	}

	// 获取总数
	if err := tx.Count(&total).Error; err != nil {
		return response.InternalServerError(c, "Database error")
	}

	// 获取LLM消息列表
	offset := (req.Page - 1) * req.Limit
	if err := tx.Offset(offset).Limit(req.Limit).Order("created_at DESC").Find(&messages).Error; err != nil {
		return response.InternalServerError(c, "Database error")
	}

	// 转换为响应格式
	rows := make([]LLMMessageRow, 0, len(messages))
	for _, msg := range messages {
		row := LLMMessageRow{
			ID:             msg.ID,
			ConversationID: msg.ConversationID,
			Role:           string(msg.Role), // 转换 types.Role 为 string
			Content:        msg.Content,
			CreatedAt:      msg.CreatedAt.Unix(),
		}

		// 添加调试字段（如果存在）
		if msg.FinishReason != "" {
			row.FinishReason = &msg.FinishReason
		}
		if msg.Model != "" {
			row.Model = &msg.Model
		}
		if msg.PromptTokens > 0 {
			row.PromptTokens = &msg.PromptTokens
		}
		if msg.CompletionTokens > 0 {
			row.CompletionTokens = &msg.CompletionTokens
		}
		if msg.TotalTokens > 0 {
			row.TotalTokens = &msg.TotalTokens
		}
		if msg.ProcessingTime > 0 {
			row.ProcessingTimeMs = &msg.ProcessingTime
		}

		rows = append(rows, row)
	}

	return response.Success(c, GetLLMMessagesResponse{
		Rows:       rows,
		Total:      total,
		Page:       req.Page,
		Limit:      req.Limit,
		TotalPages: (total + int64(req.Limit) - 1) / int64(req.Limit),
	})
}

// GetLLMMessageDetail 获取LLM消息详情（包含完整调试信息）
func (h *AdminHandler) GetLLMMessageDetail(c echo.Context) error {
	req := new(GetLLMMessageDetailRequest)
	if err := c.Bind(req); err != nil {
		return response.BadRequest(c, "Invalid request format")
	}

	var message entity.LLMMessage
	if err := h.db.First(&message, "id = ?", req.MessageID).Error; err != nil {
		return response.NotFound(c, "Message not found")
	}

	// 转换为详情响应格式
	detail := LLMMessageDetail{
		LLMMessageRow: LLMMessageRow{
			ID:             message.ID,
			ConversationID: message.ConversationID,
			Role:           string(message.Role), // 转换 types.Role 为 string
			Content:        message.Content,
			CreatedAt:      message.CreatedAt.Unix(),
		},
		RawRequestBody:  message.RawRequestBody,
		RawResponseBody: message.RawResponseBody,
	}

	// 添加调试字段（如果存在）
	if message.FinishReason != "" {
		detail.FinishReason = &message.FinishReason
	}
	if message.Model != "" {
		detail.Model = &message.Model
	}
	if message.PromptTokens > 0 {
		detail.PromptTokens = &message.PromptTokens
	}
	if message.CompletionTokens > 0 {
		detail.CompletionTokens = &message.CompletionTokens
	}
	if message.TotalTokens > 0 {
		detail.TotalTokens = &message.TotalTokens
	}
	if message.ProcessingTime > 0 {
		detail.ProcessingTimeMs = &message.ProcessingTime
	}

	return response.Success(c, detail)
}
